using System;
using System.Collections.Generic;
using System.Text;
using CSF.Communications.Sdp.ServiceLogic.Entities;
using Microsoft.RuleEngine;
using Microsoft.BizTalk.RuleEngineExtensions;
using System.Xml;
using CSF.Communications.Sdp.ServiceLogic.Exceptions;
using CSF.Communications.Sdp.ServiceLogic.DataAccess;
using System.Configuration;


namespace CSF.Communications.Sdp.ServiceLogic.Utilities
{
    public class RulePolicyProvider
    {
        #region ExecutePolicy
        /// <summary>
        /// 
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        public CSF_MID ExecutePolicy(CSF_MID mid, string policyName, int majorVersion, int minorVersion)
        {

            CSF_MID mid_final = null;
            try
            {
                Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver dd = new Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver(ConfigurationSettings.AppSettings["BiztalkDatabaseServer"].ToString(), ConfigurationSettings.AppSettings["BizTalkRuleEngineDb"].ToString());
                RuleStore sqlrs;
                sqlrs = dd.GetRuleStore();
                RuleSetInfoCollection rss = new RuleSetInfoCollection();
                rss = sqlrs.GetRuleSets(policyName, RuleStore.Filter.Latest);
                if (rss.Count != 1)
                {
                    throw new ApplicationException();
                }
                RuleSet ruleset = sqlrs.GetRuleSet(rss[0]);
                RuleEngineComponentConfiguration fr = new RuleEngineComponentConfiguration("BT.Communications.Sdp.ServiceLogic.Utilities", "MyBizTalkApplication.FactRetriever.myFactRetriever");
                RuleSetExecutionConfiguration rsCfg = ruleset.ExecutionConfiguration;
                rsCfg.FactRetriever = fr;
                PolicyTester policyTester = new PolicyTester(ruleset);
                XmlDocument midXml = new XmlDocument();
                midXml.LoadXml(mid.SerializeObject());
                TypedXmlDocument mid_doc = new TypedXmlDocument("Microsoft.Csf.Sbe.OrderHandling.ServiceLogic.Schema.Mid", midXml);
                try
                {
                    policyTester.Execute(mid_doc);
                }
                catch (Exception e)
                {
                    throw e;
                }
                mid_final = CSF_MID.DeSerializeObject(mid_doc.Document.InnerXml);
                policyTester.Dispose();

            }
            catch (Exception ex)
            {
                throw new SDPSystemException(Convert.ToInt64(SDPSystemError.SDPPolicyExecutionException), ex.Message);
            }
            return mid_final;
        }

        #endregion
    }
}
